import { Response } from "express";
import { apiLogger } from "../../logger";
import { ITokenRequest } from "../tokenMiddleware";

export enum ResponseCode {
  /**
   * 2000
   */
  PASS = 2000,
  /**
   * 4000 - 错误的请求，参数有误
   */
  ERROR = 4000,
  /**
   * 4004 - 没有找到或资源不存在
   */
  NOT_ASSETS = 4004,
  /**
   * 4003 - 没有token，没有权限
   */
  NOT_ALLOW = 4003,
  /**
   * 5000 - 服务器内部错误
   */
  UNKNOWN = 5000,
}

export type ResponseBody = {
  code: ResponseCode,
  msg: string | string[]
  data: object | []
};

export default class ResponseHelper {

  /**
   * 响应一个成功数据
   * @param result 
   * @param res 
   */
  static sendSuccess(result: ResponseBody, res: Response) {

    res.send(result)
  }

  /**
   * 响应一个错误数据
   * @param error 
   * @param res 
   */
  public static sendError(result: ResponseBody, res: Response, req?: ITokenRequest) {

    if (req) {
      const email = req.EMAIL || "unknown"
      const method = req.method || "unknown"
      const baseUrl = req.baseUrl || "unknown"
      const body = JSON.stringify(req.body) || "unknown"
      const query = JSON.stringify(req.query) || "unknown";
      const params = JSON.stringify(req.params) || "unknown";
      const response = JSON.stringify(result) || "unknown";
      apiLogger.debug("errorMiddleware", {
        email,
        method,
        baseUrl,
        body,
        params,
        query,
        response
      })
    }

    let err: string;
    if (Array.isArray(result.msg)) {
      err = result.msg.join(";");
    } else {
      err = result.msg
    }

    // 完成响应
    res.send({
      ...result,
      msg: err
    })

  }

  /**
   * 响应客户端请求
   * @param result 
   * @param res 
   */
  public static send(result: ResponseBody, res: Response, req?: ITokenRequest | Request) {
    if (result.code === 2000) {
      ResponseHelper.sendSuccess(result, res)
    } else {
      ResponseHelper.sendError(result, res, req as ITokenRequest)
    }
  }

}